package com.university.mentalhealthplatform.global.ratelimited;

import com.university.mentalhealthplatform.exception.TooManyRequestsException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@Component
public class RateLimiterInterceptor implements HandlerInterceptor {

    @Autowired
    private RateLimiterService rateLimiterService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String clientIp = request.getRemoteAddr();

        // 检查限流，如果触发限流则返回错误信息
        if (rateLimiterService.isRateLimited(clientIp)) {
            long cooldown = rateLimiterService.getCooldownRemaining(clientIp);
            throw new TooManyRequestsException("请求过于频繁，请在 " + cooldown + " 秒后重试");
        }

        return true;
    }
}
